<template>
  <div class="block">
    <el-upload
      class="avatar-uploader"
      :action="imgHead"
      :headers="head"
      :show-file-list="false"
      accept=".jpg,.jpeg,.png,.gif"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl1" :src="imageUrl1|fullImagePath" class="avatar"/>
      <i v-else class="el-icon-plus avatar-uploader-icon">
        <span class="Warning">上传图片</span>
      </i>
    </el-upload>
    <span style="color: #dddddd;">提示：仅支持jpg格式</span>
  </div>
</template>

<script>
  export default {
    name: "image-upload",
    props: {
      /* 初始值 */
      value: {
        type: String,
        default: () => {
          return null;
        }
      },
    },
    data() {
      return {
        imgHead: window.api.uploadUrl,
        head: {
          appKey: window.sessionStorage.getItem("appKey"),
          Authorization: window.sessionStorage.getItem("token")
        },
        imageUrl1: ""
      }
    },
    watch: {
      value() {
        this.imageUrl1 = this.value;
      }
    },
    methods: {
      handleAvatarSuccess(file) {
        this.imageUrl1 = file.newFileName;
        this.$emit("input", file.newFileName);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === "image/jpg";
        const isJPEG = file.type === "image/jpeg";
        const isGIF = file.type === "image/gif";
        const isPNG = file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 10;
        if (!isJPEG && !isPNG && !isGIF) {
          this.$message.error("上传图片只能是 JPG/GIF/PNG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传图片大小不能超过 10MB!");
        }
        return (isJPEG || !isGIF || !isPNG) && isLt2M;
      }
    }
  }
</script>

<style scoped lang="less">

  .avatar-uploader {
    .el-upload--text {
      img {
        object-fit: cover;
      }

      .avatar-uploader-icon {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        line-height: 30px;
        color: #ccc;

        &::before {
          font-weight: bold;
        }

        span {
          font-size: 15px;
          display: block;
          margin-top: 5px;
        }
      }
    }
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 100px;
    text-align: center;
    border: 1px solid #e9e9e9;
    border-radius: 5px;
  }
</style>
